//
//  WCIKeepAlivePlayer.m
//  WCImApp
//
//  Created by alfie on 2020/9/9.
//  Copyright © 2020 WCImApp. All rights reserved.
//

#import "WCIKeepAlivePlayer.h"
#import "QARtcEngine.h"
#import "AFModule/AFTimer.h"
#import <AVFoundation/AVAudioPlayer.h>
static NSInteger MaxAliveTime = 600; // 最大保活时长，10分钟
static NSInteger _beginTime;
@implementation WCIKeepAlivePlayer

#pragma mark - 定时器
static AFTimer *_timer;
+ (AFTimer *)timer {
    if (!_timer) {
        _timer = [AFTimer GCDTimerWithInterval:60 target:self selector:@selector(timerAction) userInfo:nil repeats:YES queue:nil];
    }
    return _timer;
}


+ (void)timerAction {
    NSLog(@"-------------------------- 定时器方法 --------------------------");
    if (NSDate.date.timeIntervalSince1970 - _beginTime >= MaxAliveTime) {
        [_player stop];
        [_timer invalidate];
        MWLogCategory(MOLogCategoryKeepAlive, @"到达最大时长关闭保活，keepAlive--close--MaxAliveTime");
    } else {
        MWLogCategory(MOLogCategoryKeepAlive, @"每分钟记录一次保活状态，keepAlive--status--live");
    }
}

#pragma mark - 无声音乐播放器
static AVAudioPlayer *_player;
+ (AVAudioPlayer *)player {
    if (!_player) {
        NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"5s静音.mp3" withExtension:nil];
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
        [_player prepareToPlay];
        _player.numberOfLoops = -1;
    }
    return _player;
}

+ (void)applicationWillEnterForeground {
    if (_player) [self.player stop];
    [_timer invalidate];
    MWLogCategory(MOLogCategoryKeepAlive, @"进入前台关闭保活，keepAlive--close--EnterForeground");
}

+ (void)applicationDidEnterBackground {
    if (!QARtcEngine.isBusy) {
        // 判断时间，如果是1点到7点，这个时间段不播放，减小电量损耗
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        dateformatter.timeZone =  [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
        dateformatter.dateFormat = @"HH";
        NSString *hStr = [dateformatter stringFromDate:NSDate.date];
        int h = hStr.intValue;
        if (h >= 1 && h < 7) {
//            MOLog(@"-------------------------- 不播放 时间啊：%@ --------------------------", hStr);
            [_player stop];
            [_timer invalidate];
            return;
        }
        
        _beginTime = NSDate.date.timeIntervalSince1970;
//        MOLog(@"-------------------------- 时间啊：%@ %ld--------------------------", hStr, _beginTime);
        [self.timer fire];
        [AVAudioSession.sharedInstance setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
        [AVAudioSession.sharedInstance setActive:YES error:nil];
        MWLogCategory(MOLogCategoryKeepAlive, @"开启保活，keepAlive--start");
//        MOLog(@"-------------------------- 播放无声音乐 --------------------------");
        [self.player play];
    }
}





@end
